package consys.social.nosql.dao.hbase;

import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;

/**
 * extends HTable
 *
 * @author Petr Kunc
 */
public class HBaseTable extends HTable implements HBase {

    public HBaseTable(Configuration config, String table) throws IOException {
        super(config, table);
    }

    public HBaseTable(String table) throws IOException {
        super(table);
    }

    @Override
    public boolean replace(final Put put) throws IOException {
        if (put.isEmpty()) {
            throw new IllegalArgumentException("No col families to insert!");
        }
        if (!this.add(put)) {
            put(put);
            return true;
        } else {
            delete(new Delete(put.getRow()));
        }
        return false;
    }

    @Override
    public boolean deleteIfTrue(final Delete delete) throws IOException {
        if (delete.isEmpty()) {
            throw new IllegalArgumentException("No cols to delete!");
        }
        return this.checkAndDelete(delete.getRow(),
                delete.getFamilyMap().keySet().iterator().next(),
                delete.getFamilyMap().values().iterator().next().get(0).getQualifier(),
                Bytes.toBytes(true), delete);
    }

    @Override
    public boolean add(final Put put) throws IOException {
        if (put.isEmpty()) {
            throw new IllegalArgumentException("No col families to insert!");
        }
        return this.checkAndPut(put.getRow(),
                put.getFamilyMap().keySet().iterator().next(),
                put.getFamilyMap().values().iterator().next().get(0).getQualifier(),
                null, put);
    }

    @Override
    public long increment(String row, String family, String col, long value) throws IOException {
        return this.incrementColumnValue(Bytes.toBytes(row), Bytes.toBytes(family), Bytes.toBytes(col), value);
    }

    @Override
    public long increment(byte[] row, String family, String col, long value) throws IOException {
        return this.incrementColumnValue(row, Bytes.toBytes(family), Bytes.toBytes(col), value);
    }

    @Override
    public boolean deleteIfGet(Get get, Delete delete) throws IOException {
        boolean exists = this.exists(get);
        if (exists) {
            this.delete(delete);
        }
        return exists;
    }
}
